Introduction
A 2-dimensional array in C is an array of arrays, often used to represent matrices or grids. It stores elements in a tabular format, organized into rows and columns.
Declaration and Initialization of 2-Dimensional Array
Declaration
data_type array_name[rows][columns];
- data_type: Type of elements in the array (e.g., int, float, char).
- rows: Number of rows in the array.
- columns: Number of columns in the array.
Examples
- Declaration without initialization:
int matrix[3][4]; - Declaration with partial initialization:
int matrix[3][4] = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12} }; - Compiler infers dimensions for partial initialization:
int matrix[][4] = { {1, 2, 3, 4}, {5, 6, 7, 8} };
Accessing and Modifying Elements
2-D array elements are accessed using two indices:
- The first index specifies the row.
- The second index specifies the column.
matrix[row][column] = value; // Assigns a value to the element
int x = matrix[1][2]; // Retrieves the element at row 1, column 2
Example: Iterating Through a 2-D Array
#include < stdio.h>
int main() {
int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
// Printing the 2-D array
for (int i = 0; i < 2; i++) { // Iterate through rows
for (int j = 0; j < 3; j++) { // Iterate through columns
printf("matrix[%d][%d] = %d\n", i, j, matrix[i][j]);
}
}
return 0;
}
Output:
matrix[0][0] = 1
matrix[0][1] = 2
matrix[0][2] = 3
matrix[1][0] = 4
matrix[1][1] = 5
matrix[1][2] = 6
Memory Layout
In C, 2-D arrays are stored in row-major order, meaning that elements in the same row are stored in contiguous memory locations.
int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
Stored in memory as:
1, 2, 3, 4, 5, 6
Passing 2-D Arrays to Functions
When passing a 2-D array to a function, the number of columns must be specified, but the number of rows is optional.
#include < stdio.h>
void printMatrix(int rows, int cols, int matrix[rows][cols]) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}
int main() {
int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
printMatrix(2, 3, matrix); // Pass the array to the function
return 0;
}
Common Use Cases
- Matrices: Mathematical computations involving matrices.
- Grids: Representing games like tic-tac-toe, chess boards, etc.
- Tables: Storing tabular data such as student scores or sales data.